package shop.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import shop.dao.BaseOrderDao;
import shop.dao.CartDao;
import shop.dao.OrderInfoDao;
import shop.dao.UserDao;
import shop.dao.impl.BaseOrderDaoImpl;
import shop.dao.impl.CartDaoImpl;
import shop.dao.impl.OrderInfoDaoImpl;
import shop.dao.impl.UserDaoImpl;
import shop.entity.BaseOrder;
import shop.entity.User;
import shop.entity.dto.CartDTO;
import shop.entity.vo.OrderVO;
import shop.util.DBUtil;

@WebServlet("/BaseOrderServlet")
public class BaseOrderServlet extends BaseServlet {
	private BaseOrderDao dao = new BaseOrderDaoImpl();
	private CartDao cartDao = new CartDaoImpl();
	private OrderInfoDao infoDao = new OrderInfoDaoImpl();
	private UserDao userDao = new UserDaoImpl();
	
	//下订单
	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//下订单需要对三张表进行数据操作：1、基础订单表（存储订单收获地址和金额）；2、订单详情表（存储订单中的商品种类和数量）；3、购物车表（顺带清空购物车，下完单购物车商品要消失）
		//下订单会在基础订单表添加一行记录
		//一个订单可能会购买多种商品，每种商品需要在订单详情表中添加一行
		//购物车要删除订单详情表中添加的商品
		
		//-----------------------------------begin获取下单需要的基础数据---------------------------------------
		HttpSession session = request.getSession();
		//从session取出登录用户信息
		User user = (User)session.getAttribute("user");
		
		//准备基础订单表所需的数据
		String userAddress = request.getParameter("userAddress");//收货地址
		String name = request.getParameter("name");//收货人
		String phone = request.getParameter("phone");//收货人手机号
		double amount = Double.parseDouble(request.getParameter("amount"));//订单金额
		//订单号：日期+时间+4位随机数
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(new Date());
		int n = (int) (Math.random()*9000+1000);
		String orderNo = time+n;
		
		//准备订单详情表需要的数据
		List<CartDTO> cartList = (List<CartDTO>) session.getAttribute("cartList");
		
		//-----------------------------------end获取下单需要的基础数据---------------------------------------
		
		//-------------------begin执行对三张表的数据操作，要么都成功，要么都失败，放在一个事务里----------------------------
		Connection conn = DBUtil.getConnection();
		try {
			conn.setAutoCommit(false);//关闭事务自动提交 
			//1、向基础订单表添加数据
			String sql1 = "INSERT INTO `interesting_shop_db`.`t_base_order`(`user_id`, `account`, `user_address`,  `amount`, `order_no`, `name`, `phone`) VALUES (?,?,?,?,?,?,?)";
			PreparedStatement ps1 = conn.prepareStatement(sql1);
			ps1.setInt(1, user.getId());
			ps1.setString(2, user.getAccount());
			ps1.setString(3, userAddress);
			ps1.setDouble(4, amount);
			ps1.setString(5, orderNo);
			ps1.setString(6, name);
			ps1.setString(7, phone);
			ps1.executeUpdate();
			
			//2、向订单详情表添加数据
			for(CartDTO cart:cartList) {
				String sql2 ="INSERT INTO `interesting_shop_db`.`t_order_info`( `order_no`, `goods_id`, `buy_num`, `amount`) VALUES (?,?,?,?)";
				PreparedStatement ps2 = conn.prepareStatement(sql2);
				ps2.setString(1, orderNo);
				ps2.setInt(2, cart.getGid());
				ps2.setInt(3, cart.getNum());
				ps2.setDouble(4, cart.getNum()*cart.getPrice());
				ps2.executeUpdate();
			}
			
			//3、删除订单中的购物车表中的数据
			String sql3 = "delete from t_cart where user_id = "+user.getId();
			PreparedStatement ps3 = conn.prepareStatement(sql3);
			ps3.executeUpdate();
			
			session.removeAttribute("cartList");
			session.setAttribute("totalPrice", 0.0);
			conn.commit();//手动提交事务
		}catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();//回滚事务
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally {
			try {
				conn.setAutoCommit(true);//开启事务自动提交
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		//-------------------begin执行对三张表的数据操作，要么都成功，要么都失败，放在一个事务里----------------------------
		
		//订单成功后从账户余额扣钱，并累计消费金额
		dao.pay(amount,user.getId());
		dao.consume(amount,user.getId());
		
		
		session.setAttribute("orderNo", orderNo);
		session.setAttribute("amount", amount);
		user.setBalance(user.getBalance()-amount);
		user.setConsume(user.getConsume()+amount);
		session.setAttribute("user", user);
		response.sendRedirect("buyCarThree.jsp");
	}
	
	//查询所有订单
	public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		List<BaseOrder> orderList = dao.findAll(user.getId());
		System.out.println(orderList);
		session.setAttribute("orderList", orderList);
		response.sendRedirect("memberOrder.jsp");
	}
	
	//根据订单号查看订单详情
	public void findDetails(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String orderNo = request.getParameter("orderNo");
		List<OrderVO> orderVOList = dao.findDetails(orderNo);
		session.setAttribute("orderVOList", orderVOList);
		response.sendRedirect("memberOrder2.jsp");
	}


}
